package main

import (
	"fmt"

	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

/*
*
SharedInformer
*/
func main() {
	config, err := clientcmd.BuildConfigFromFlags("", "/home/cloudea/.kube/config")
	if err != nil {
		panic(err)
	}
	clientSet, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	// 初始化
	sharedInformerFactory := informers.NewSharedInformerFactory(clientSet, 0)

	// 查询Pod数据
	podInformer := sharedInformerFactory.Core().V1().Pods()

	// podInformer.Informer().AddEventHandler()
	// podInformer.Informer().GetIndexer()

	// 生成一个indexer方便查询
	lister := podInformer.Lister()

	// 启动informer
	sharedInformerFactory.Start(nil)

	// 等数据同步
	sharedInformerFactory.WaitForCacheSync(nil)

	// 利用indexer获取数据
	// for _ = range time.Tick(time.Second, 3) {...} // 可以循环获取
	pods, err := lister.List(labels.Everything())
	if err != nil {
		panic(err)
	}

	for _, items := range pods {
		fmt.Printf("namesapce: %v, name: %v \n", items.GetNamespace(), items.GetName())
	}

}
